package com.question;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;

public class QuestionHM3 extends Thread{

    String key;
    String value;
    TestDo testDo;

    public QuestionHM3(String key,String key2, String value) {
        this.key = key+key2;
        this.value = value;
        testDo=TestDo.getInstance();
    }

    public static void main(String[] args)
    {
        QuestionHM3 th1=new QuestionHM3("1","","1");
        QuestionHM3 th2=new QuestionHM3("1","","2");
        QuestionHM3 th3=new QuestionHM3("3","","3");
        QuestionHM3 th4=new QuestionHM3("4","","4");

        System.out.println(Thread.currentThread().getName()+"begin:"+System.currentTimeMillis()/1000);
        th1.start();
        th2.start();
        th3.start();
        th4.start();

    }


    public void run() {
        testDo.process(key,value);
    }
}
 class TestDo{

     private static TestDo instance=new TestDo();
     public static TestDo getInstance()
     {
         return instance;
     }
     HashSet hashSet=new HashSet();
     CopyOnWriteArrayList keys=new CopyOnWriteArrayList();
     public void process(Object key,String value)
    {
        //////////////////////有的时候会四个线程同步进行，是因为有问题吗
        Object o=key;
        synchronized (QuestionHM3.class)
        {
            if (!keys.contains(o))
            {
                keys.add(o);
            }else
            {
                for(Iterator iter=keys.iterator();iter.hasNext();)
                {
                    Object oo=iter.next();
                    if (oo.equals(o))
                    {
                        o=oo;
                    }
                }
            }
        }
/*        if (!hashSet.contains(key))
        {
            hashSet.add(o);
        }
        else
        {
            Iterator<Integer> iterator = hashSet.iterator();
            while (iterator.hasNext())
            {
                Object temp= iterator.next();
                if (temp.equals(o))
                {
                    o=temp;
                }
            }
        }*/



        synchronized (o) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "——" + key + ":" + value + System.currentTimeMillis() / 1000);
        }

    }

 }
